package com.franklin.ideaplugin.maphelper.completion.result;

import cn.hutool.core.collection.CollectionUtil;
import com.franklin.ideaplugin.maphelper.beans.colmember.IColMember;
import com.franklin.ideaplugin.maphelper.completion.result.impl.DefaultMapLookupElementBuilder;
import com.franklin.ideaplugin.maphelper.completion.result.impl.FastJsonMapLookupElementBuilder;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.psi.PsiExpression;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Ye Junhui
 * @since 2024/3/7
 */
public class MapLookupElementFactory {

    private final static List<IMapLookupElementBuilder> mapLookupElementBuilderList = ImmutableList.of(
            FastJsonMapLookupElementBuilder.INSTANCE,
            DefaultMapLookupElementBuilder.INSTANCE
    );

    /**
     * 构建提示
     * @param psiExpression
     * @param colMembers
     * @return
     */
    public static List<LookupElement> buildLookupElement(PsiExpression psiExpression, Collection<? extends IColMember> colMembers){
        if (CollectionUtil.isEmpty(colMembers)){
            return Collections.emptyList();
        }
        for (IMapLookupElementBuilder mapLookupElementBuilder : mapLookupElementBuilderList) {
            if (mapLookupElementBuilder.support(psiExpression)){
                return colMembers.stream()
                        .flatMap(mapMember -> {
                            //内容
                            String maybeText = mapMember.getValueText();
                            //提示
                            List<LookupElementBuilder> lookupElementBuilderList = mapLookupElementBuilder.buildLookupElement(psiExpression, mapMember);
                            return lookupElementBuilderList.stream()
                                    .map(lookupElementBuilder -> lookupElementBuilder.withTailText("  " + maybeText));
                        })
                        .collect(Collectors.toList());

            }
        }
        return Lists.newArrayList();
    }
}
